package aplug.data.db;


import java.util.concurrent.Callable;

import javax.inject.Inject;
import javax.inject.Singleton;

import aplug.data.db.common.RxDbHelper;
import aplug.data.db.mode.CollectInfo;
import aplug.data.db.mode.CollectInfoDao;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 惠安 on 2017/11/23.
 */


@Singleton
public class CollectInfoHelper extends RxDbHelper<CollectInfo, Long, CollectInfoDao> {

    /**
     * 家
     */
    public static final Long HOME_ID = 1L;
    /**
     * 公司
     */
    public static final Long COMPANY_ID = 2L;

    @Inject
    public CollectInfoHelper(DbOpenHelper helper) {
        super(helper.getDaoSession().getCollectInfoDao());

        count().subscribeOn(Schedulers.io())
                .filter(count -> count <= 0)
                .doOnNext(count -> {
                    insert(new CollectInfo(HOME_ID, "家", null, null, null))
                            .subscribe();
                    insert(new CollectInfo(COMPANY_ID, "公司", null, null, null))
                            .subscribe();

                })
                .subscribe();
    }

    public Observable<CollectInfo> findByLatLon(double latitude, double longitude) {
        return Observable.fromCallable(new Callable<CollectInfo>() {
            @Override
            public CollectInfo call() throws Exception {
                CollectInfo unique = mDao.queryBuilder()
                        .where(CollectInfoDao.Properties.Lat.eq(latitude),
                                CollectInfoDao.Properties.Lon.eq(longitude))
                        .unique();
                return unique;
            }
        });
    }

    public static String getDefaultCollectName(int collectId) {
        if (collectId == HOME_ID) {
            return "家";
        } else if (collectId == COMPANY_ID) {
            return "公司";
        }
        return "未设置";
    }
}
